package com.api.gbhg.huangwm.budget;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.api.gbhg.huangwm.dao.RevenueBudgetDao;
import com.api.gbhg.huangwm.dao.YuSuanTiaoZhengDao;
import com.customization.commons.LogTool;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Huangwm
 * @Date 2022-10-14
 * @Version 1.0
 * @Description TODO 预算调整 减少
 **/
public class BudgetReduction implements Action {
    private LogTool logTool = new LogTool("/log/gbhg/huangwm/ystz/BudgetReduction",false);
    private static String YJ ;//科目级别
    private static String XJ ;//科目下级

    private String nodetype;

    public String getNodetype() {
        return nodetype;
    }

    public void setNodetype(String nodetype) {
        this.nodetype = nodetype;
    }

    @Override
    public String execute(RequestInfo requestInfo) {
        //先校验
        int requestid = requestInfo.getRequestManager().getRequestid();
        int billid = requestInfo.getRequestManager().getBillid();
        String tablename = requestInfo.getRequestManager().getBillTableName();
        int formid = requestInfo.getRequestManager().getFormid();
        logTool.writeLog("预算减少调整 requestid="+requestid +" nodetype="+this.nodetype);
        if(this.nodetype.equals("") || this.nodetype == null){
            requestInfo.getRequestManager().setMessagecontent("未获取到节点附加操作配置的nodetype");
            requestInfo.getRequestManager().setMessageid(requestid+"");
            return FAILURE_AND_CONTINUE;
        }
        BaseBean baseBean = new BaseBean();
        YJ = baseBean.getPropValue("Verification","yj");
        XJ = baseBean.getPropValue("Verification","xj");
        String dzxm = "" ,ysnd = "" ,szdlhsdw = "";
        Property[] properties = requestInfo.getMainTableInfo().getProperty();
        for(Property property : properties){
            if(property.getName().equals("dzxm")){
                dzxm = property.getValue();
            }else if(property.getName().equals("ysnd")){
                ysnd = property.getValue();
            }else if(property.getName().equals("szdlhsdw")){
                szdlhsdw = property.getValue();
            }
        }
        if(dzxm.equals("") || dzxm.equals("null")){
            requestInfo.getRequestManager().setMessagecontent("未获取到调整项目的字段值");
            requestInfo.getRequestManager().setMessageid(requestid+"");
            return FAILURE_AND_CONTINUE;
        }
        if(ysnd.equals("") || ysnd.equals("null")){
            requestInfo.getRequestManager().setMessagecontent("未获取到预算年度的字段值");
            requestInfo.getRequestManager().setMessageid(requestid+"");
            return FAILURE_AND_CONTINUE;
        }
        if(szdlhsdw.equals("") || szdlhsdw.equals("null")){
            requestInfo.getRequestManager().setMessagecontent("未获取到独立核算单位的字段值");
            requestInfo.getRequestManager().setMessageid(requestid+"");
            return FAILURE_AND_CONTINUE;
        }
        RecordSetTrans rst = new RecordSetTrans();
        rst.setAutoCommit(false);
        if(this.nodetype.equals("create")){
            RecordSet rs = new RecordSet();
            String JJFL = new YuSuanTiaoZhengDao().getJjfl_DtTablesNoZSXM(formid);//获取细化经济分类明细表名称
            RecordSet rs2 = new RecordSet();
            String getDt4 = "select * from "+JJFL+" where mainid="+billid;
            rs.execute(getDt4);
            while (rs.next()) {
                String bmyszcjjfl = rs.getString("bmyszcjjfl");
                Double dzje = rs.getDouble("dzje");
                Double syed = getJingFeiSyed(rs2,dzxm,bmyszcjjfl);
                if(dzje>0) {
                    if ((syed - dzje) < 0) {
                        requestInfo.getRequestManager().setMessagecontent("经济分类[" + bmyszcjjfl + "]实际剩余额度[" + syed + "]不足以减少[" + dzje + "]");
                        requestInfo.getRequestManager().setMessageid(requestid + "");
                        return FAILURE_AND_CONTINUE;
                    }
                }
            }
        }else{
            RecordSet rs = new RecordSet();
            try {
                String JJFL = new YuSuanTiaoZhengDao().getJjfl_DtTablesNoZSXM(formid);//获取细化经济分类明细表名称
                RecordSet rs2 = new RecordSet();
                String getDt4 = "select * from "+JJFL+" where mainid="+billid;
                rs.execute(getDt4);
                while (rs.next()) {
                    String bmyszcjjfl = rs.getString("bmyszcjjfl");
                    Double dzje = rs.getDouble("dzje");
                    Double syed = getJingFeiSyed(rs2,dzxm,bmyszcjjfl);
                    if(dzje>0){
                        //调整金额大于0才进行判断调整
                        if((syed-dzje)<0){
                            rst.rollback();
                            requestInfo.getRequestManager().setMessagecontent("经济分类["+bmyszcjjfl+"]实际剩余额度["+syed+"]不足以减少["+dzje+"]");
                            requestInfo.getRequestManager().setMessageid(requestid+"");
                            return FAILURE_AND_CONTINUE;
                        }
                        String setJingFei = "UPDATE uf_jingfei SET ze=ze-(?),syed=syed-(?) WHERE lcjlid=? AND bmzcjjfl=? ";
                        logTool.writeLog(setJingFei+"  "+dzje +" "+dzje+" "+dzxm+" "+bmyszcjjfl);
                        boolean thisResult = rst.executeUpdate(setJingFei,dzje,dzje,dzxm,bmyszcjjfl);
                        if(!thisResult){
                            rst.rollback();
                            requestInfo.getRequestManager().setMessagecontent("经济分类["+bmyszcjjfl+"]执行减少SQL失败");
                            requestInfo.getRequestManager().setMessageid(requestid+"");
                            return FAILURE_AND_CONTINUE;
                        }
                    }
                }
                try {
                    List<String> HPQD = new YuSuanTiaoZhengDao().getHpqd_DtTablesNoZSXM(formid);//获取核批渠道明细表名称
                    //获取上年结转和当年预算的明细数据

                    RecordSet snjz = new RecordSet();
                    snjz.execute("select * from "+HPQD.get(1) +" where mainid="+billid);
                    int sn = 1;
                    while (snjz.next()){
                        //非中央收入分类
                        String zcqd = snjz.getString("zcqd");
                        //收入类型
                        String srlx = snjz.getString("srlx");
                        //中央财政拨款项目
                        String zyczbksr = snjz.getString("zyczbksr");
                        //地方财政拨款项目上年结转
                        String dfczbkxmsnjz = snjz.getString("dfczbkxmsnjz");
                        String yslylx = "上年结转核批";
                        Double ysjs = snjz.getDouble("ysjs");//上年结转渠道减少金额
                        Integer did = snjz.getInt("did");
                        if(ysjs>0){
                            //Double syed = getJingFeiLaiYuanSyed(rs2,dzxm,yslylx,srlx,zcqd, dfczbkxmsnjz,zyczbksr);
                            Double syed = getJingFeiLaiYuanSyedV2(rs2,did);
                            if((syed-ysjs)<0){
                                rst.rollback();
                                requestInfo.getRequestManager().setMessagecontent("上年结转第"+sn+"行渠道剩余金额:"+syed+" 不足以减少:"+ysjs);
                                requestInfo.getRequestManager().setMessageid(requestid+"");
                                return FAILURE_AND_CONTINUE;
                            }
                            String setJingFeiLaiYuan = "UPDATE uf_jingfeilaiyuan SET je=je-(?),syed=syed-(?) WHERE id=? ";
                            boolean thisResult = rst.executeUpdate(setJingFeiLaiYuan,ysjs,ysjs,did);
                            if(!thisResult){
                                rst.rollback();
                                requestInfo.getRequestManager().setMessagecontent("上年结转第"+sn+"行渠道执行减少SQL失败");
                                requestInfo.getRequestManager().setMessageid(requestid+"");
                                return FAILURE_AND_CONTINUE;
                            }
                            String setUrl = getUrlSQL_SN(dzxm,srlx,zcqd, dfczbkxmsnjz,zyczbksr,ysjs);
                            boolean thisResult2 = rst.executeUpdate(setUrl);
                            logTool.writeLog("更新上年核批记录SQL："+setUrl);
                            logTool.writeLog("更新上年核批记录结果："+thisResult2);
                            if(!thisResult2){
                                rst.rollback();
                                requestInfo.getRequestManager().setMessagecontent("上年结转第"+sn+"行渠道在减少uf_ysbzyxeshpsj_dt1执行SQL失败");
                                requestInfo.getRequestManager().setMessageid(requestid+"");
                                return FAILURE_AND_CONTINUE;
                            }
                        }
                        sn ++;
                    }

                    RecordSet dnys = new RecordSet();
                    dnys.execute("select * from "+HPQD.get(0) +" where mainid="+billid);
                    int dn = 1;
                    while (dnys.next()){
                        //非中央收入分类
                        String zcqd = dnys.getString("zcqd");
                        //收入类型
                        String srlx = dnys.getString("srlx");
                        //中央财政拨款项目
                        String zyczbksr = dnys.getString("zyczbksr");
                        //地方财政拨款项目上年结转
                        String dfczbkxmdnys = dnys.getString("dfczbkxmdnys");
                        String yslylx = "当年预算核批";
                        Double ysjs = dnys.getDouble("ysjs");//上年结转渠道减少金额
                        Integer did = dnys.getInt("did");
                       if(ysjs>0){
                           //Double syed = getJingFeiLaiYuanSyed(rs2,dzxm,yslylx,srlx,zcqd, dfczbkxmsnjz,zyczbksr);
                           Double syed = getJingFeiLaiYuanSyedV2(rs2,did);
                           if((syed-ysjs)<0){
                               rst.rollback();
                               requestInfo.getRequestManager().setMessagecontent("当年预算第"+dn+"行渠道剩余金额:"+syed+" 不足以减少:"+ysjs);
                               requestInfo.getRequestManager().setMessageid(requestid+"");
                               return FAILURE_AND_CONTINUE;
                           }
                           String setJingFeiLaiYuan = "UPDATE uf_jingfeilaiyuan SET je=je-(?),syed=syed-(?) WHERE id=? ";
                           boolean thisResult = rst.executeUpdate(setJingFeiLaiYuan,ysjs,ysjs,did);
                           if(!thisResult){
                               rst.rollback();
                               requestInfo.getRequestManager().setMessagecontent("当年预算第"+dn+"行渠道执行减少SQL失败");
                               requestInfo.getRequestManager().setMessageid(requestid+"");
                               return FAILURE_AND_CONTINUE;
                           }
                           String setUrl = getUrlSQL_DN(dzxm,srlx,zcqd, dfczbkxmdnys,zyczbksr,ysjs);
                           boolean thisResult2 = rst.executeUpdate(setUrl);
                           logTool.writeLog("更新当年核批记录SQL："+setUrl);
                           logTool.writeLog("更新当年核批记录结果："+thisResult2);
                           if(!thisResult2){
                               rst.rollback();
                               requestInfo.getRequestManager().setMessagecontent("当年预算第"+dn+"行渠道在减少uf_ysbzyxeshpsj_dt2执行SQL失败");
                               requestInfo.getRequestManager().setMessageid(requestid+"");
                               return FAILURE_AND_CONTINUE;
                           }
                       }
                        dn ++;
                    }
                    //更新收入预算
                    List<Map<String,String>> snjzDatas = getSNDatas(HPQD.get(1),billid+"");
                    List<Map<String,String>> dnysDatas = getDNDatas(HPQD.get(0),billid+"");
                    Map<String, Object> result = new RevenueBudgetDao().RevenueBudgetReturnV2(snjzDatas,dnysDatas,Integer.parseInt(szdlhsdw),ysnd);
                    logTool.writeLog("预算减少释放结果："+ JSONObject.toJSONString(result));
                    if(!result.get("code").equals("1")){
                        String f1 = result.get("f1").toString();
                        String f2 = result.get("f2").toString();
                        String f3 = result.get("f3").toString();
                        String f4 = result.get("f4").toString();
                        String f5 = result.get("f5").toString();
                        String f6 = result.get("f6").toString();
                        String f7 = result.get("f7").toString();
                        String f8 = result.get("f8").toString();
                        String msg = "<br />"+f1+f2+f3+f4+f5+f6+f7+f8;
                        rst.rollback();
                        requestInfo.getRequestManager().setMessageid(requestInfo.getRequestid());
                        requestInfo.getRequestManager().setMessagecontent("根据预算减少金额释放收入预算失败 "+msg);
                        return  FAILURE_AND_CONTINUE;
                    }

                }catch (Exception e){
                    rst.rollback();
                    e.printStackTrace();
                    requestInfo.getRequestManager().setMessagecontent("更新预算核批渠道额度异常 "+e.getMessage());
                    requestInfo.getRequestManager().setMessageid(requestid+"");
                    return FAILURE_AND_CONTINUE;
                }
                //更新预算信息主表的总额
                rst.executeUpdate("UPDATE dbo.uf_jingfei_version SET yszje=(SELECT SUM(ze) FROM dbo.uf_jingfei WHERE lcjlid=lcjlsqjlid) WHERE lcjlsqjlid="+dzxm);
            }catch (Exception e){
                rst.rollback();
                e.printStackTrace();
                requestInfo.getRequestManager().setMessagecontent("校验/更新jingfei额度异常 "+e.getMessage());
                requestInfo.getRequestManager().setMessageid(requestid+"");
                return FAILURE_AND_CONTINUE;
            }

        }

        rst.commit();
        return SUCCESS;
    }

    /**
     * 根据id获取中央下级收入的所有上级id 包含本身
     * @param id
     * @return
     */
    public List<String> getSuperiorId(String id){
        List<String> list = new ArrayList<>();
        RecordSet rs = new RecordSet();
        String sql = " select sjzxsr from  uf_zyczbksr_xj where id = "+id+" ";
        rs.executeQuery(sql);
        rs.next();
        if (StrUtil.isNotEmpty(rs.getString("sjzxsr"))){
            List<String> sjzxsr = getSuperiorId(rs.getInt("sjzxsr")+"");
            list.addAll(sjzxsr);
        }
        list.add(String.valueOf(id));
        return list;
    }

    public Double getJingFeiSyed(RecordSet rs , String dzxm, String bmyszcjjfl){
        rs.execute("select * from uf_jingfei where lcjlid="+dzxm +" and bmzcjjfl="+bmyszcjjfl);
        if(rs.next()){
            return rs.getDouble("syed");
        }
        return 0.00;
    }

    public Double getJingFeiLaiYuanSyed(RecordSet rs,String dzxm,String yslylx,String srlx,String srfl,String dfczbkxm,String zyczbksr){
        String baseSql = "SELECT * FROM uf_jingfeilaiyuan  \n" +
                "WHERE lcid="+dzxm+" and yslylx='"+yslylx+"' and srlx="+srlx+" \n";
        if(Integer.parseInt(srlx)==0){
            //财政拨款
            baseSql += " and zyczbksy='"+zyczbksr+"'";
        }else{
            if(srfl.equals("5") || srfl.equals("8") ){
                baseSql += " and zcqd="+srfl+" and zcdfczbkxm="+dfczbkxm;
            }else {
                baseSql += " and zcqd=" + srfl ;
            }
        }
        rs.execute(baseSql);
        if(rs.next()){
            return rs.getDouble("syed");
        }
        return 0.00;
    }
    public Double getJingFeiLaiYuanSyedV2(RecordSet rs,Integer did){
        String baseSql = "SELECT * FROM uf_jingfeilaiyuan WHERE id="+did;
        rs.execute(baseSql);
        if(rs.next()){
            return rs.getDouble("syed");
        }
        return 0.00;
    }

    public String getJFLYSQL(String dzxm,String yslylx,String srlx,String srfl,String dfczbkxm,String zyczbksr,Double ysjs){
        String setSql = "update uf_jingfeilaiyuan  set je=je-("+ysjs+"),syed=syed-("+ysjs+") WHERE lcid="+dzxm+" and yslylx='"+yslylx+"' and srlx="+srlx+" \n";
        if(Integer.parseInt(srlx)==0){
            //财政拨款
            setSql += " and zyczbksr='"+zyczbksr+"'";
        }else{
            if(srfl.equals("5") || srfl.equals("8") ){
                setSql += " and zcqd="+srfl+" and zcdfczbkxm="+dfczbkxm;
            }else {
                setSql += " and zcqd=" + srfl ;
            }
        }
        return setSql;
    }

    public String getUrlSQL_SN(String dzxm,String srlx,String srfl,String dfczbkxm,String zyczbksr,Double ysjs){
        String setSql = "update uf_ysbzyxeshpsj_dt1  set hpje=hpje-("+ysjs+") "+
                " WHERE mainid="+dzxm+" and srlx="+srlx+" \n";
        if(Integer.parseInt(srlx)==0){
            //财政拨款
            setSql += " and zyczbksr='"+zyczbksr+"'";
        }else{
            if(srfl.equals("5") || srfl.equals("8") ){
                setSql += " and zcqd="+srfl+" and dfczbkxmsnjz="+dfczbkxm;
            }else {
                setSql += " and zcqd=" + srfl ;
            }
        }
        return setSql;
    }
    public String getUrlSQL_DN(String dzxm,String srlx,String srfl,String dfczbkxm,String zyczbksr,Double ysjs){
        String setSql = "update uf_ysbzyxeshpsj_dt2  set hpje=hpje-("+ysjs+") "+
                " WHERE mainid="+dzxm+" and srlx="+srlx+" \n";
        if(Integer.parseInt(srlx)==0){
            //财政拨款
            setSql += " and zyczbksr='"+zyczbksr+"'";
        }else{
            if(srfl.equals("5") || srfl.equals("8") ){
                setSql += " and zcqd="+srfl+" and dfczbkxmdnys="+dfczbkxm;
            }else {
                setSql += " and zcqd=" + srfl ;
            }
        }
        return setSql;
    }
    /**
     * 根据上年结转核批明细表和流程mainid获取明细数据
     * @param snDetailTable
     * @param mainid
     * @return
     */
    public List<Map<String,String>> getSNDatas(String snDetailTable, String mainid){
        List<Map<String,String>> snjzDatas = new ArrayList<>();
        RecordSet rs = new RecordSet();
        String sql = "select id,srlx,zyczbksr,zcqd,dfczbkxmsnjz,hpje,ysjs from "+snDetailTable+" where mainid="+mainid;
        rs.execute(sql);
        while (rs.next()){
            if(rs.getDouble("ysjs")>0){
                Map<String,String> data = new HashMap<>();
                data.put("id", rs.getString("id"));//明细表id
                data.put("srlx", rs.getString("srlx"));//收入预算 0和1 代表财政拨款和非财政拨款
                data.put("zyczbksr", Util.null2String(rs.getString("zyczbksr")));//中央财政拨款收入时的财政拨款预算来源
                data.put("zcqd", Util.null2String(rs.getString("zcqd")));//非财政拨款时的非财政拨款预算来源
                data.put("dfczbkxmsnjz", Util.null2String(rs.getString("dfczbkxmsnjz")));//非财政拨款时的非财政拨款项目
                data.put("hpje", rs.getString("ysjs"));//拿预算减少金额
                snjzDatas.add(data);
            }
        }
        return snjzDatas;
    }

    /**
     * 根据当年预算核批明细表和流程mainid获取明细数据
     * @param dnDetailTable
     * @param mainid
     * @return
     */
    public List<Map<String,String>> getDNDatas(String dnDetailTable,String mainid) {
        List<Map<String,String>> dnysDatas = new ArrayList<>();
        RecordSet rs = new RecordSet();
        String sql = "select id,srlx,zyczbksr,zcqd,dfczbkxmdnys,hpje,ysjs from "+dnDetailTable+" where mainid="+mainid;
        rs.execute(sql);
        while (rs.next()){
            if(rs.getDouble("ysjs")>0) {
                Map<String, String> data = new HashMap<>();
                data.put("id", rs.getString("id"));//明细表id
                data.put("srlx", rs.getString("srlx"));//收入预算 0和1 代表财政拨款和非财政拨款
                data.put("zyczbksr", rs.getString("zyczbksr"));//中央财政拨款收入时的财政拨款预算来源
                data.put("zcqd", rs.getString("zcqd"));//非财政拨款时的非财政拨款预算来源
                data.put("dfczbkxmdnys", rs.getString("dfczbkxmdnys"));//非财政拨款时的非财政拨款项目
                data.put("hpje", rs.getString("ysjs"));//拿预算减少金额
                dnysDatas.add(data);
            }
        }
        return dnysDatas;
    }
}
